// pages/coupon/balance-detail.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  data: {
    balanceList: [],
    isLoading: false,
    page: 1,
    pageSize: 20,
    hasMore: true,
    emptyTip: '暂无账户余额变动记录'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '余额变动明细',
    });
    this.loadBalanceDetail();
  },

  /**
   * 返回上一页
   */
  onTapBack: function() {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 获取余额明细数据
   */
  loadBalanceDetail: function() {
    if (this.data.isLoading || !this.data.hasMore) {
      return;
    }

    this.setData({
      isLoading: true
    });

    // 调用API获取余额变动记录
    api.user.getBalanceLogs({
      page: this.data.page,
      page_size: this.data.pageSize
    })
    .then(res => {
      if (res && res.success && res.data) {
        // 格式化时间和处理金额显示
        const list = (res.data.list || []).map(item => {
          return {
            ...item,
            time: utils.formatTimestamp(item.created_at || item.time),
            // 确保金额有正负号显示
            display_amount: (item.amount > 0 ? '+' : '') + item.amount.toFixed(2)
          };
        });

        // 合并数据
        const balanceList = [...this.data.balanceList, ...list];
        
        this.setData({
          balanceList: balanceList,
          page: this.data.page + 1,
          hasMore: list.length >= this.data.pageSize
        });
      } else {
        wx.showToast({
          title: res.message || '获取余额明细失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error('获取余额明细失败:', err);
      wx.showToast({
        title: '获取余额明细失败',
        icon: 'none'
      });
    })
    .finally(() => {
      this.setData({
        isLoading: false
      });
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.hasMore) {
      this.loadBalanceDetail();
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    this.setData({
      balanceList: [],
      page: 1,
      hasMore: true
    });
    
    this.loadBalanceDetail();
    wx.stopPullDownRefresh();
  }
}); 